import { defineStore } from "pinia";
import { ref } from "vue";
import { login, getUserInfo } from "@/service/api/auth";

export const useAuthStore = defineStore(
  "auth",
  () => {
    const token = ref("");
    const userInfo = ref({
      _id: "",
      name: "",
      permissions: []
    });

    function setToken(newToken: string) {
      token.value = newToken;
    }

    function setUserInfo(newUserInfo: any) {
      userInfo.value = newUserInfo;
    }

    async function loginAction(
      {
        username,
        password
      }: {
        username: string;
        password: string;
      },
      callback?: () => void
    ) {
      const { data, error } = await login({ username, password });
      if (error) {
        return false;
      }
      setToken(data.token);
      await getUserInfoAction();
      if (typeof callback === "function") {
        callback();
      }
    }

    async function getUserInfoAction() {
      if (!token.value) {
        return false;
      }
      const { data, error } = await getUserInfo();
      if (error) {
        return false;
      }
      setUserInfo(data);
      return data;
    }

    return {
      token,
      setToken,
      userInfo,
      setUserInfo,
      loginAction,
      getUserInfoAction
    };
  },
  {
    persist: true
  }
);
